package com.smart.four.ioc.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static javafx.scene.input.KeyCode.V;

/**
 * 反射
 *
 * @author junrui.wang
 * @create 2018/4/18
 */
public class ReflectTest {
    public static Car initByDefaultConst() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //通过类装载器获取Car对象
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("com.smart.four.ioc.reflect.Car");

        //获取类的默认构造器对象并通过他实例化对象Car
        Constructor<Car> cons = clazz.getDeclaredConstructor((Class[]) null);
        Car car = cons.newInstance();

        //通过反射方法设置属性
        Method setBrand = clazz.getMethod("setBrand", String.class);
        setBrand.invoke(car, "buick");

        Method setColor = clazz.getMethod("setColor", String.class);
        setColor.invoke(car, "blue");

        Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car, 150);

        return car;
    }


    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Car car = ReflectTest.initByDefaultConst();
        car.introduce();
    }
}
